package com.dlc.shop.listener;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dlc.shop.bean.enums.EsOperationType;
import com.dlc.shop.bean.enums.ProdStatusEnums;
import com.dlc.shop.bean.event.EsProductUpdateEvent;
import com.dlc.shop.bean.event.ProdChangeStatusEvent;
import com.dlc.shop.bean.event.SigningCategoryInvalidEvent;
import com.dlc.shop.bean.model.Product;
import com.dlc.shop.service.BasketService;
import com.dlc.shop.service.ProductService;
import lombok.AllArgsConstructor;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author lth
 * @Date 2021/9/6 13:49
 */
@Component("signingCategory")
@AllArgsConstructor
public class SigningCategoryListener {

    private final ProductService productService;
    private final BasketService basketService;
    private final ApplicationEventPublisher applicationEventPublisher;

    @EventListener(SigningCategoryInvalidEvent.class)
    public void signingCategoryListener(SigningCategoryInvalidEvent event) {
        Long shopId = event.getShopId();
        Long categoryId = event.getCategoryId();
        // 查询该店铺下使用了该分类并且处于上架状态的商品
        List<Product> productList = productService.list(Wrappers.lambdaQuery(Product.class).eq(Product::getShopId, shopId).eq(Product::getCategoryId, categoryId).eq(Product::getStatus, ProdStatusEnums.NORMAL.getValue()));
        if (CollUtil.isEmpty(productList)) {
            return;
        }
        List<Long> pIds = productList.stream().map(Product::getProdId).collect(Collectors.toList());
        // 下架商品
        productService.changeStatusByProdIds(pIds, ProdStatusEnums.SHOP_OFFLINE.getValue());
        // 清除商品缓存
        productService.removeProductCacheByProdIds(pIds);
        // 清除购物车缓存
        List<String> userIds = basketService.listUserIdByProdIds(pIds);
        basketService.removeCacheByUserIds(userIds);
        for (Product product : productList) {
            applicationEventPublisher.publishEvent(new ProdChangeStatusEvent(product, ProdStatusEnums.SHOP_OFFLINE.getValue()));
        }
        applicationEventPublisher.publishEvent(new EsProductUpdateEvent(null, pIds, EsOperationType.UPDATE_BATCH));
    }
}
